package com.lbkj.ops.controller;

import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import com.lbkj.ops.common.exception.Http400Exception;
import com.lbkj.ops.common.jpa.JpaBaseEntity;
import com.lbkj.ops.common.util.SessionUtils;
import com.lbkj.ops.dao.OpsWarUploadDao;
import com.lbkj.ops.model.OpsWarUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author jian.liu
 * @date 2020/11/5
 */
@RestController
@RequestMapping("/api/wars")
public class WarController {

    @Value("${ops.upload.path}")
    private String opsUploadPath;

    @Autowired
    private OpsWarUploadDao opsWarUploadDao;

    @PostMapping
    public void upload(@RequestPart MultipartFile file) {
        String bucket = SessionUtils.getLoginUser().getAccount();
        String filename = file.getOriginalFilename();
        final Path path = Paths.get(opsUploadPath, bucket, LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE), filename);
        final File toFile = path.toFile();
        if(!toFile.exists()) {
            toFile.mkdirs();
        }
        try {
            file.transferTo(toFile);
        } catch (IOException e) {
            throw new Http400Exception("文件上传异常：" + e.getMessage());
        }
        // 记录上传记录
        OpsWarUpload opsWarUpload = new OpsWarUpload();
        opsWarUpload.setFilename(filename);
        opsWarUpload.setFilePath(path.toString());
        opsWarUpload.setUploader(bucket);
        opsWarUploadDao.save(opsWarUpload);
    }

    @GetMapping
    public Page<OpsWarUpload> list(@RequestParam(required = false, defaultValue = "1") Integer page,
                                @RequestParam(required = false, defaultValue = "15") Integer size) {
        String account = SessionUtils.getLoginUser().getAccount();
        PredicateBuilder<OpsWarUpload> pb = Specifications.<OpsWarUpload>and();
        if(!"admin".equals(account)) {
            pb.eq("uploader", account);
        }
        PageRequest pageRequest = PageRequest.of(page-1, size, Sort.by(Sort.Order.desc(JpaBaseEntity.UPDATE_TIME)));
        return opsWarUploadDao.findAll(pb.build(), pageRequest);
    }

}
